require([
    'frender3x/app/AppMap',
    'esri/geometry/Extent',
    'dojo/on',
    'dojo/text!frender3x/template/RenderView.ejs',
    'dojo/text!frender3x/template/ProjectView.ejs',
    'dojo/text!frender3x/template/ParameterView.ejs',
    'dojo/text!frender3x/template/ConnectorView.ejs',
    'dojo/ready'
],
function(AppMap, Extent,
         on,
         RenderViewTmpl, ProjectViewTmpl, ParameterViewTmpl, ConnectorViewTmpl){
    //-----------------------------model------------------------------
    var ConfModel = Backbone.Model.extend({

    });

    var ProjectModel = Backbone.Model.extend({
        initialize:function(){

        }
    });

    var ConnectUserModel = Backbone.Model.extend({
        defaults:{}
    })


    //----------------------------collection-------------------------
    var ProjectCollection = Backbone.Collection.extend({
        model:ProjectModel,
        initialize:function(){

        },
        fetchProjects:function(){
            //$.ajax({
            //
            //})
            return [
                {
                    name:'2011年6月5日降水过程'
                },
                {
                    name:'2012年6月5日降水过程'
                },
                {
                    name:'2013年6月5日降水过程'
                },
                {
                    name:'2014年6月5日降水过程'
                }
            ]
        }
    });
    var ConnectUserCollection = Backbone.Collection.extend({
        model:ConnectUserModel,
        initialize:function(){

        }
    });


    //-----------------------------view-------------------------------
    var MapView = Backbone.View.extend({
        initialize:function(opt){
            this.options = {
                mapdiv:'mapdiv'
            };
            _.extend(this.options, opt);
        },
        render:function(){

        }

    });

    var RenderView = Backbone.View.extend({
        events:{
            'click .render-control-panel-btn':'_controlPanelBtn_clickHandler'
        },
        initialize:function(opt){
            this.options = {

            };
            this.eventBus = opt.eventBus;
            this.template = _.template(RenderViewTmpl);
            this.elems = {
                'controlBtn':'.render-control-panel-btn',
                'slider':'.render-progress-panel-slider',
                'toggleRemote':'.render-control-toggle-remote'
            };
            this.currentPlayStep = -1;
            this.stepCount = -1;
            this.playState = false;
            this.eventBus.on('render-play', this.renderPlay, this);
        },
        render:function(){
            $(this.el).html(this.template({
                title:'二维水动力'
            }))
        },
        setFRender:function(fr){
            this.frender = fr;
        },
        setStepCount:function(count){
            this.stepCount = count;
        },
        _controlPanelBtn_clickHandler:function(evt){
            $(this.elems.controlBtn).removeClass('btn-primary');
            $(evt.currentTarget).addClass('btn-primary');

            var data = $(evt.currentTarget).attr('data');
            switch (data){
                case 'play':
                    this._playSlider();
                    break;
                case 'resume':
                    break;
                case 'stop':
                    this._stopSlider();
                    break;
            }


        },
        _playSlider:function(){
            if ($(this.elems.toggleRemote).attr('checked', true)){
                this.eventBus.trigger('render-toggle-remote');
            }
            var self = this;
            self.playState = true;
            self.currentPlayStep = 0;
            self._progress();
            this.frender.play(200);
        },
        _progress:function(){
            var self = this;
            console.log('222');
            setTimeout(function(){
                console.log(self.playStep + ' ' + self.currentPlayStep);
                if (self.playState && self.currentPlayStep <= self.stepCount){
                    console.log('111');


                    var cent = Math.floor(self.currentPlayStep / self.stepCount  * 100, 2);
                    $(self.elems.slider).html(''+cent+'%');
                    $(self.elems.slider).attr('aria-valuenow', cent);
                    $(self.elems.slider).attr('style', 'width:'+ cent +'%;');

                    self.currentPlayStep++;
                    self._progress();
                }else{
                    $(self.elems.controlBtn).removeClass('btn-primary');
                }
            }, 200);

        },
        _stopSlider:function(){
            this.playState = false;
            this.frender.stop();
        },
        renderPlay:function(){
            this._playSlider();
        }
    });

    var ProjectView = Backbone.View.extend({
        events:{
          'click .project-proj-item':'_projItem_clickHandler'
        },
        initialize:function(){
            this.template = _.template(ProjectViewTmpl);

            this.elems = {
                'projItem':'.project-proj-item'
            }

            this.projCollection = new ProjectCollection();
            this.projCollection.on('add', this._addItem, this);
        },
        render:function(){
            $(this.el).html(this.template({
                list:this.projCollection.toJSON()
            }));
            return this;
        },
        fetchProjects:function(){
            var arr = this.projCollection.fetchProjects();
            this.projCollection.set(arr);
        },
        _addItem:function(){
            this.render();
        },
        _projItem_clickHandler:function(evt){
            $(this.elems.projItem).removeClass('active');
            $(evt.currentTarget).addClass('active');
        }
    });

    var ParameterView = Backbone.View.extend({
        initialize:function(){
            this.template = _.template(ParameterViewTmpl);
        },
        render:function(){
            $(this.el).html(this.template({

            }));
            return this;
        }
    });

    var ConnectorView = Backbone.View.extend({
        events:{
            'click .connector-connect-control-panel-btn[data=connect]':"connectBtn_clickHandler",
            'click .connector-connect-user-list-item':"userListItemClick",
            'click .connector-chain-command':'commandItemClick'
        },
        initialize:function(opt){
            this.template = _.template(ConnectorViewTmpl);
            this.elems = {
                "connectBtn":".connector-connect-control-panel-btn[data=connect]",
                "connectTestBtn":".connector-connect-control-panel-btn[data=test]",
                "roomField":"#connector-connect-parameter-gate",
                "ipField":"#connector-connect-parameter-address",
                "userListItem":".connector-connect-user-list-item"
            };
            this.userCollection = new ConnectUserCollection();
            this.userCollection.on("add", this._addUser, this);
            this.userCollection.on("remove", this._removeUser, this);
            this.activeUserTarget = null;

            this.eventBus = opt.eventBus;

            var self = this;
            pomelo.on("onAdd", function(data){
                self.pomeloOnAdd(data);
            });

            pomelo.on("onLeave", function(data){
                self.pomeloOnLeave(data);
            });

            pomelo.on("onPlayRender", function(data){
                self.onPlayRender();
            });

            this.eventBus.on('render-toggle-remote', this.renderToggleRemote, this);
            this.eventBus.on('map-did-zoom-end', this.mapDidZoomEnd, this);
            this.eventBus.on('map-did-pan-end', this.mapDidPanEnd, this);

        },
        render:function(){
            $(this.el).html(this.template({
                chainUserList:this.userCollection.toJSON()
            }));
            return this;
        },
        connectBtn_clickHandler:function(){
            var self = this;
            this.queryEntry(self.uid, function(host, port){
                pomelo.init({
                    host:host,
                    port:port,
                    log:true
                }, function(){
                    var route = 'connector.entryHandler.enter';
                    pomelo.request(route, {
                        username:self.username,
                        rid:self.gate(),
                    }, function(data){
                        console.log(data);
                        var m = [];
                        for (var i=0; i < data.users.length; i++){
                            if (data.users[i] != self.username){
                                m.push({username:data.users[i]});
                            }
                        }
                        self.userCollection.set(m);
                    }
                    )
                })
            })
        },
        queryEntry:function(uid, callback){
            var self = this;
            var route = 'gate.gateHandler.queryEntry';
            var ip = self.address();
            pomelo.init({
                    host:ip.split(":")[0],
                    port:ip.split(":")[1],
                    log:true
                },
                function(){
                    pomelo.request(route, {
                            uid:uid
                        },
                        function(data){
                            pomelo.disconnect();

                            if (data.code === 500){
                                console.log("error");
                                return;
                            }

                            callback(data.host, data.port);
                        })
                }
            );
        },
        setConnectInfo:function(conf){
            this.uid = conf.uid;
            this.username = conf.username;
        },
        gate:function(){
            return $(this.elems.roomField).val();
        },
        setGate:function(gate){
            return $(this.elems.roomField).val(gate);
        },
        address:function(){
            return $(this.elems.ipField).val();
        },
        setAddress:function(address){
            $(this.elems.ipField).val(address);
        },
        _addUser:function(){
            this.render();
        },
        _removeUser:function(){
            this.render();
        },
        pomeloOnAdd:function(data){
            this.userCollection.add({username:data.user});
        },
        pomeloOnLeave:function(data){
            console.log('leave---------------');
            console.log(data);
            var model = this.userCollection.findWhere({
                username:data.user
            });
            this.userCollection.remove(model);
        },
        userListItemClick:function(evt){
            $(this.elems.userListItem).removeClass("active");
            $(evt.currentTarget).addClass("active");
            this.activeUserTarget = $(evt.currentTarget).attr('username');
        },
        commandItemClick:function(){

        },
        onPlayRender:function(){
            this.eventBus.trigger('render-play');
        },
        renderToggleRemote:function(){
            var route = 'chat.chatHandler.playRender';
            var target = (this.activeUserTarget)?this.activeUserTarget:'*';
            var msg = '{"type":"play"}';
            pomelo.request(route, {
                rid:this.gate(),
                content:msg,
                from:this.username,
                target:target
            },function(data){
                console.log(data);
            })
        },
        mapDidZoomEnd:function(data){
            var route = 'chat.chatHandler.mapNormalCommand';
            var target = (this.activeUserTarget)?this.activeUserTarget:'*';
            var msg = JSON.stringify(data);
            pomelo.request(route, {
                rid:this.gate(),
                content:msg,
                from:this.username,
                target:target
            },function(data){
                console.log(data);
            })
        },
        mapDidPanEnd:function(data){

            var route = 'chat.chatHandler.mapNormalCommand';
            var target = (this.activeUserTarget)?this.activeUserTarget:'*';
            var msg = JSON.stringify(data);
            console.log(msg);
            pomelo.request(route, {
                rid:this.gate(),
                content:msg,
                from:this.username,
                target:target
            },function(data){
                //console.log(data);
            })
        }
    });


    //----------------------------instance---------------------------
    function guid() {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        }
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
            s4() + '-' + s4() + s4() + s4();
    }
    var uid = "web_" + navigator.appCodeName + "_" + parseInt(Math.random()*1000);// + "-" + guid();
    var username = uid;
    esriConfig.defaults.io.proxyUrl = "http://192.168.1.152:3000/proxy";
    esriConfig.defaults.io.alwaysUseProxy = false;
    var appmap = new AppMap('mapdiv', {
        center:[119.464,29.233],
        zoom:15
    });

    var eventBus = _.extend({}, Backbone.Events);

    appmap.on('tile-loaded', function(){
        var confModel = new ConfModel();
        var mapView = new MapView({
            el:'mapdiv',
            mapdiv:'mapdiv',
            eventBus:eventBus
        });
        mapView.render();

        var renderView = new RenderView({
            el:'#fun-render',
            eventBus:eventBus
        });
        renderView.render();

        var projView = new ProjectView({
            el:'#fun-project',
            eventBus:eventBus
        });
        projView.render();
        projView.fetchProjects();

        var paraView = new ParameterView({
            el:'#fun-parameter',
            eventBus:eventBus
        });
        paraView.render();

        var connectorView = new ConnectorView({
            el:'#fun-connector',
            eventBus:eventBus
        });
        connectorView.render();
        connectorView.setGate('scene-chain');
        connectorView.setConnectInfo({
            uid:uid,
            username:username
        })
        connectorView.setAddress('192.168.1.152:3014');

        renderView.setFRender(appmap.frender);
        appmap.frender.setCenter([13295246.9230999980,3408246.9544000030]);
        appmap.frender.setPictureUrl('/images/png2/');
        var pad=(num, n)=> {
            var len = num.toString().length;
            while(len < n) {
                num = "0" + num;
                len++;
            }
            return num;
        };
        var names = [];
        for (var i=0; i < 153; i++){
            names.push('Reclass_n'+pad(i, 4)+'_tin.png');
        }
        appmap.frender.setPictureNames(names);
        renderView.setStepCount(153);
        appmap.frender.show();
        appmap.frender.init();

        //appmap.map.on('click',(e)=>{
        //    console.log(e);
        //})


        eventBus.on('pomelo-on-map-normal-command', function(data){
            console.log(data);
            var json = JSON.parse(data.msg);
            switch (json.type){
                case 'zoom-end':
                    appmap.map.setZoom(json.level);
                    break;
                case 'pan-end':
                    var ep = json.event.desExtent;
                    appmap.map.setExtent(new Extent(ep.xmin,ep.ymin, ep.xmax, ep.ymax, appmap.map.spatialReference));
                    break;
            }
        });
        pomelo.on('onMapNormalCommand', function(data){
            eventBus.trigger('pomelo-on-map-normal-command', data);
        });

        appmap.map.on('zoom-end', function(){
            eventBus.trigger('map-did-zoom-end', {
                level:appmap.map.getLevel(),
                type:'zoom-end'
            });
        });

        var panStartExtent = {};
        appmap.map.on('pan-start', function(evt){
            panStartExtent = evt.extent;
        });

        appmap.map.on('pan-end', function(evt){
            eventBus.trigger('map-did-pan-end', {
                event:{
                    oriExtent:panStartExtent,
                    desExtent:evt.extent,
                    delta:evt.delta
                },
                type:'pan-end'
            })
        })
    });
    window.appmap = appmap;
    appmap.init();


    function connectHandler(){

    }

    function queryEntry(uid, callback){

    }

})